package com.tc.socket.config;

import lombok.extern.slf4j.Slf4j;
import org.apache.activemq.command.SessionId;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.SubscribableChannel;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.messaging.SubProtocolWebSocketHandler;

import java.util.HashMap;
import java.util.Map;

/**
 * @Auther: tianchao
 * @Date: 2022/11/8 11:28
 * @Description:
 */
@Slf4j
public class CustomerSubProtocolWebSocketHandler extends SubProtocolWebSocketHandler {
    private Map<String,WebSocketSession> map = new HashMap<>();

    /**
     * Create a new {@code SubProtocolWebSocketHandler} for the given inbound and outbound channels.
     *
     * @param clientInboundChannel  the inbound {@code MessageChannel}
     * @param clientOutboundChannel the outbound {@code MessageChannel}
     */
    public CustomerSubProtocolWebSocketHandler(MessageChannel clientInboundChannel, SubscribableChannel clientOutboundChannel) {
        super(clientInboundChannel, clientOutboundChannel);
    }

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        map.put(session.getId(), session);
        log.info("===>afterConnectionEstablished sessionId: {},session: {}",session.getId(),session);
        super.afterConnectionEstablished(session);
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
        super.afterConnectionClosed(session, closeStatus);
        log.info("===>afterConnectionClosed session: {},closeStatus:{}",session,closeStatus);
    }

    public void close(String sessionId){
        WebSocketSession webSocketSession = this.getWebSocketSessionById(sessionId);
        try {
            this.afterConnectionClosed(webSocketSession, CloseStatus.NORMAL);
        } catch (Exception e) {
            log.error("close error", e);
            e.printStackTrace();
        }
    }
    public WebSocketSession getWebSocketSessionById(String sessionId){
        return map.get(sessionId);
    }
}
